<?php


namespace Streetlamp;

use Streetlamp\exception\ExceptionHandler;
use think\Config;
use think\Exception;
use think\Log;

class Server
{
    private $config;

    private $serverName = '';

    public function __construct($serverName = 'streetlamp')
    {
        $this->serverName = $serverName;
        $this->config     = Config::get('streetlamp_server')[$this->serverName] ?? [];
        if (empty($this->config))
            throw new Exception('config error');
    }

    public function run()
    {
        try {
            $allMethod = (new Scanner($this->config))->scan();
            switch ($this->config['server_type']) {
                case 'swoole':
                    \Swoole\Runtime::enableCoroutine(true);
                    $server = new \Hprose\Swoole\Server('tcp://' . $this->config['host'] . ':' . $this->config['port']);
                    $server->set($this->config['setting'] ?? []);
                    break;
                case 'socket':
                default:
                    $server = new \Hprose\Socket\Server('tcp://' . $this->config['host'] . ':' . $this->config['port']);
                    break;
            }
            //添加中间件
            if (!empty($this->config['middlewares'])) {
                foreach ($this->config['middlewares'] as $middleware) {
                    $middleware = new $middleware;
                    if ($middleware instanceof Middleware) {
                        $server->addInvokeHandler([$middleware, 'handle']);
                    }
                }
            }
            //添加方法
            foreach ($allMethod as $ClassMethod) {
                $server->addFunction([$ClassMethod['class'], $ClassMethod['method']], $ClassMethod['alias'], array('passContext' => true));
            }
            //服务抛异常后在这里处理
            $server->onSendError = function ($error, \stdClass $context) {
                (new ExceptionHandler())->report($error);
            };
            $server->start();
        } catch (\Throwable $e) {
            throw $e;
        }
    }
}